package com.punisher.excel;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import java.io.*;
import java.util.Collections.*;
import java.util.*;
import java.text.SimpleDateFormat;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
import org.springframework.mail.javamail.JavaMailSenderImpl;

public class App {

    private static final Logger log = LoggerFactory.getLogger(App.class);
    private Config cfg;
    private org.springframework.context.support.AbstractApplicationContext ctx;

    public static void main(String[] args) {
        if (args.length == 0) {
            System.out.println("No params?");
            // java -cp .;classes;lib/* -Dlog.base=C:/apps/projects/workspace/dietreport-app/target com.punisher.diet.App file:/C:/apps/projects/workspace/dietreport-app/src/main/resources/DietApplicationContext.xml
            // /home7/dopiatac/bin/jre1.6.0_21/bin/java -cp .:classes:lib/* -Dlog.base=/home7/dopiatac/logs com.punisher.diet.App file:/home7/dopiatac/bin/dietapp/classes/UnixDietApplicationContext.xml
            return;
        }
        try {
            log.debug("###############################");
            log.debug("Main loading spring application context = " + args[0]);
            org.springframework.context.support.FileSystemXmlApplicationContext fc = new org.springframework.context.support.FileSystemXmlApplicationContext(args[0]);
            log.debug("Main context loaded");
            log.debug("###############################");

            log.debug("###############################");
            log.debug("Main loading spring components");
            // NOTE: all are singletons, widen objects
            App loader = new App();
            loader.ctx = (org.springframework.context.support.AbstractApplicationContext) fc;
            loader.cfg = (Config) loader.ctx.getBean("loaderConfig");
            loader.runApp();
            log.debug("Done loading files");
            log.debug("###############################");
        } catch (Exception e) {
            log.error("###############################");
            log.error("Exception in main block = " + e.toString());
            java.io.StringWriter tw = new java.io.StringWriter();
            java.io.PrintWriter pw = new java.io.PrintWriter(tw, false);
            e.printStackTrace(pw);
            String msg = tw.getBuffer().toString();
            pw.close();
            log.error("Exception trace = " + msg);
            log.error("###############################");
            System.exit(-1);
        }
    }

    private void runApp() throws Exception {
        String _inputMSAccessFile = cfg.getXlsInputFile();
        FileInputStream _fis = null;
        _fis = new FileInputStream(_inputMSAccessFile);
        HSSFWorkbook _workbook = new HSSFWorkbook(_fis);
        HSSFSheet _sheet = _workbook.getSheetAt(0);
        Iterator _rows = _sheet.rowIterator();
        int _rowCnt = 0, _cellDt = 0;
        SimpleDateFormat _sdfRawNumber = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat _sdfOutputDate = new SimpleDateFormat("EEEE, dd MMMM yyyy");
        int _todayDt = new Integer(_sdfRawNumber.format(new java.util.Date()));
        List<String> _headerDataArr = new ArrayList<String>();
        List<String> _rowDataArr = new ArrayList<String>();
        while (_rows.hasNext()) {
            HSSFRow row = (HSSFRow) _rows.next();
            Iterator cells = row.cellIterator();
            while (cells.hasNext()) {
                HSSFCell cell = (HSSFCell) cells.next();
                //###############################
                // HEADERS
                //###############################
                if (cell.getRowIndex() == 0) {
                    _headerDataArr.add(cell.getRichStringCellValue().getString());
                }
                if (cell.getRowIndex() > 0 && cell.getColumnIndex() == 0) {
                    try {
                        _cellDt = new Integer(_sdfRawNumber.format(cell.getDateCellValue()));
                    } catch (Exception e) {
                        // do nothing
                    }
                }
                if (_cellDt == _todayDt) {
                    _rowCnt = row.getRowNum();
                    break;
                }
            }
        }
        StringBuffer bufOut = new StringBuffer();
        if (_rowCnt > 0) {
            bufOut.append("<!DOCTYPE html>");
            bufOut.append("<html lang=\"en-US\">" + "\n");
            bufOut.append("<body>" + "\n");
            for (int j = 0; j < 8; j++) {
                if (_sheet.getRow(_rowCnt) != null) {
                    HSSFRow row = _sheet.getRow(_rowCnt);
                    bufOut.append("<table border=\"1\">" + "\n");
                    bufOut.append("<tr bgcolor=\"#99CCFF\"><td>####################################" + "</td></tr>" + "\n");
                    bufOut.append("<tr bgcolor=\"#99CCFF\"><td>Date = " + _sdfOutputDate.format(row.getCell(0).getDateCellValue()) + "</td></tr>" + "\n");
                    bufOut.append("<tr bgcolor=\"#99CCFF\"><td>####################################" + "</td></tr>" + "\n");
                    for (int i = 1; i < _headerDataArr.size(); i++) {
                        HSSFCell cell = row.getCell(i);
                        if (cell == null) {
//                            bufOut.append("<tr bgcolor=\"#FFCC66\"><td>");
//                            bufOut.append(_headerDataArr.get(i) + "=");
//                            bufOut.append("BLANK");
//                            bufOut.append("</td></tr>" + "\n");
                            continue;
                        }
                        if (cell.getCellType() == 1) {
                            bufOut.append("<tr bgcolor=\"#CCFFFF\"><td>");
                            bufOut.append("<b>" + _headerDataArr.get(i) + "</b>" + "=");
                            bufOut.append(cell.getRichStringCellValue().toString());
                            if (cell.getCellComment() != null) {
                                bufOut.append(", Comment=");
                                String commentString = cell.getCellComment().getString().getString().replace("BNP Paribas User:", "").replace("dopiata:", "");
                                commentString = commentString.trim();
                                bufOut.append(commentString);
                            } else {
                            }
                            bufOut.append("</td></tr>" + "\n");
                        } else {
//                            bufOut.append("<tr bgcolor=\"#FFCC66\"><td>");
//                            bufOut.append(_headerDataArr.get(i) + "=");
//                            bufOut.append("BLANK");
//                            bufOut.append("</td></tr>" + "\n");
                        }
                    }
                    bufOut.append("<tr bgcolor=\"#99CCFF\"><td>####################################" + "</td></tr>" + "\n");
                    bufOut.append("</table>" + "\n");
                    bufOut.append("<hr>" + "\n");
                }
                _rowCnt++;
            }
            bufOut.append("</body>" + "\n");
            bufOut.append("</html>");
        }
        _fis.close();
        String from = cfg.getMailFrom();
        String to = cfg.getMailTo();
        String cc = cfg.mailCc;
        String subject = cfg.mailSubject + " for " + _sdfOutputDate.format(new java.util.Date());
        if (bufOut.toString().length() > 0) {
            try {
                log.debug(bufOut.toString());
                JavaMailSenderImpl mailSource = cfg.getMailSource();
                MimeMessage mimeMessage = mailSource.createMimeMessage();
                mimeMessage.setFrom(new InternetAddress(from));
                Address[] sendArr = {new InternetAddress(to), new InternetAddress(cc)};
                mimeMessage.setRecipients(Message.RecipientType.TO, sendArr);
                //mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
                mimeMessage.setSubject(subject);
                mimeMessage.setContent(bufOut.toString(), "text/html");
                //mimeMessage.setText(bufOut.toString());
                mailSource.send(mimeMessage);
            } catch (Exception e) {
                throw e;
            }
        } else {
            try {
                log.debug("No date found in excel file?");
                JavaMailSenderImpl mailSource = cfg.getMailSource();
                MimeMessage mimeMessage = mailSource.createMimeMessage();
                mimeMessage.setFrom(new InternetAddress(from));
                Address[] sendArr = {new InternetAddress(to), new InternetAddress(cc)};
                mimeMessage.setRecipients(Message.RecipientType.TO, sendArr);
                mimeMessage.setSubject(subject);
                mimeMessage.setText("No date found in excel file?");
                mailSource.send(mimeMessage);
            } catch (Exception e) {
                throw e;
            }
        }
    }
}
